package com.neu.provider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import org.litepal.LitePal;

public class MyStudentContentProvider extends ContentProvider {

    private static final String STU_TABLE="student";

    public static final int QUERY_SUCCESS = 0;
    public static final int UPDATE_SUCCESS = 1;
    public static final int DELETE_SUCCESS = 2;
    public static final int INSERT_SUCCESS = 3;

    public static final String AUTHORITY = "com.neu.provider.student";

    private static final UriMatcher MURI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        MURI_MATCHER.addURI(AUTHORITY, "insert", INSERT_SUCCESS);
        MURI_MATCHER.addURI(AUTHORITY, "delete", DELETE_SUCCESS);
        MURI_MATCHER.addURI(AUTHORITY, "update", UPDATE_SUCCESS);
        MURI_MATCHER.addURI(AUTHORITY, "query", QUERY_SUCCESS);
    }

    //对数据库操作对象
    private SQLiteDatabase db;

    public MyStudentContentProvider() {
    }

    @Override
    public boolean onCreate() {
        // TODO: Implement this to initialize your content provider on startup.
        //初始化数据库
        LitePal.initialize(getContext());
        //获得实例true
        db=LitePal.getDatabase();

        return true;
    }


    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // Implement this to handle requests to delete one or more rows.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public String getType(Uri uri) {
        // TODO: Implement this to handle requests for the MIME type of the data
        // at the given URI.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        if(INSERT_SUCCESS==MURI_MATCHER.match(uri)){
            long id=db.insert(STU_TABLE,null,values);
            return ContentUris.withAppendedId(uri, id);
        }
        throw new UnsupportedOperationException("Not yet implemented");
    }


    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        // TODO: Implement this to handle query requests from clients.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        if(UPDATE_SUCCESS == MURI_MATCHER.match(uri)){
            return db.update(STU_TABLE, values, selection,selectionArgs);
        }

        throw new UnsupportedOperationException("Not yet implemented");
    }
}
